import 'package:camerawesome/camerawesome_plugin.dart';
import 'package:flutter/material.dart';
import 'package:getx_learn/app/modules/weichat_post/widgets/camera/widgets/take_photo.dart';
import 'package:getx_learn/app/modules/weichat_post/widgets/camera/widgets/take_video.dart';
import 'package:path_provider/path_provider.dart';
import 'package:uuid/uuid.dart';

/// 相机页面
class CameraPage extends StatelessWidget {
  const CameraPage(
      {super.key, this.captureMode = CaptureMode.video, this.maxVideoDuration});

  // 拍照、拍视频
  final CaptureMode captureMode;

  // 视频最大时长（单位：s）
  final Duration? maxVideoDuration;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CameraAwesomeBuilder.custom(
        builder: (cameraState, preview) {
          return cameraState.when(
              // 拍照
              onPhotoMode: (state) {
            return TakePhotoPage(cameraState: state);
          },

              // 拍视频
              onVideoMode: (state) {
            return TakeVideoPage(
              cameraState: state,
              maxVideoDuration: maxVideoDuration,
            );
          },

              // 拍摄中
              onVideoRecordingMode: (state) {
            return TakeVideoPage(
              cameraState: state,
              maxVideoDuration: maxVideoDuration,
            );
          },

              // 启动摄像头
              onPreparingCamera: (state) {
            return Center(
              child: CircularProgressIndicator(),
            );
          });
        },
        // 保存配置
        saveConfig: captureMode == CaptureMode.photo
            ? SaveConfig.photo(pathBuilder: _buildFilePath)
            : SaveConfig.video(pathBuilder: _buildFilePath),

        // 生成规则
        imageAnalysisConfig: AnalysisConfig(
          // Android 图像格式和大小
          androidOptions: AndroidAnalysisOptions.jpeg(width: 500),
        ),
      ),
    );
  }

  /// 构建文件名称
  Future<CaptureRequest> _buildFilePath(List<Sensor> sensors) async {
    // final extDir = await getApplicationDocumentsDirectory();
    final extDir = await getTemporaryDirectory();
    // 拓展名
    final extendName = captureMode == CaptureMode.photo ? "jpg" : "mp4";
    final path = '${extDir.path}/${const Uuid().v4()}.$extendName';
    return SingleCaptureRequest(path, sensors.first);
  }
}
